package com.sto.stoapp.thread;

import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.http.BaseMessage;
import com.sto.stoapp.http.HttpManager;
import com.sto.stoapp.http.MessageType;
import com.sto.stoapp.http.URLActions;
import com.sto.stoapp.http.request.LoginRequest;
import com.sto.stoapp.http.response.LoginResponse;
import com.sto.stoapp.server.StoDownServer;

import java.io.File;

/**
 * 登陆线程
 * 
 * @author mgf
 * 
 */
public class LoginThread extends BaseThread {
	private Context context;
	// 登陆请求码
	public static final int LOGIN_REQUEST_CODE = 0xff;

	private LoginRequest request;
	private Handler handler;

	public LoginThread(Context context, LoginRequest request, Handler handler) {
		super(context);
	    this.context = context;
		this.request = request;
		this.handler = handler;
		showDialog();
	}

	@Override
	public void run() {
        super.run();
		Message msg = handler.obtainMessage();
		msg.what = LOGIN_REQUEST_CODE;
		LoginResponse response = null;

		HttpManager mgr = new HttpManager();
		Gson gs = new Gson();
		String str = mgr.doPostClient(request.buildToRequestString(),
				StoFilePreference.getInstance(context).getServerIp()
						+ URLActions.LOGIN_ACTION);

		try {
			response = gs.fromJson(str, new TypeToken<LoginResponse>() {
			}.getType());
		} catch (JsonSyntaxException e) {
			e.printStackTrace();
		}

		msg.obj = response;

		if (response != null
				&& response.respCode.equals(BaseMessage.REQUEST_SUCCESS)) {

			StoFilePreference.getInstance(context).setSessionId(
					response.sessionId);
			// 下载数据
			handler.post(new RunnableUi("登陆请求成功,正在更新数据..."));
			startDown();
			int max = 0;

			for (;;) {
				try {
					sleep(30);
					max = StoDownServer.getTaskSize();
					if (max == 0) {
						break;
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}
		delApk();
		cancelDialog();
		handler.sendMessage(msg);

	}



	class RunnableUi implements Runnable {
		String msg = "";

		public RunnableUi(String msg) {
			// TODO Auto-generated constructor stub
			this.msg = msg;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			setMessage(msg);
		}

	}

	private void delApk(){
		File rootDirectory = new File(Environment.getExternalStorageDirectory()
				.getAbsolutePath());

		if(null==rootDirectory){
			return;
		}
		if(null==rootDirectory.listFiles()){
			return;
		}

		if (rootDirectory.exists()) {
			for (File f : rootDirectory.listFiles()) {
				if (f.isFile()) {
					String fileName = f.getName();
					if (fileName.endsWith(".apk") || fileName.endsWith(".APK") ) {
						f.delete();
					}
				}
			}
		}
	}

	/**
	 * 下载各类报表的线程
	 */
	private void startDown() {

		Intent downIntent = new Intent(context, StoDownServer.class);

		downIntent.putExtra(StoDownServer.SERVER_DOWN_STATUS, new int[] {
				MessageType.NEXT_SITE_CODE, MessageType.SITE_CODE_FULL,
				MessageType.PROVINCE_TYPE, MessageType.AVIATION_ROUTE,
				MessageType.PROBLEM_TYPE, MessageType.ORDER_REASON_TYPE,
				MessageType.SITE_SALEAS_TYPE, MessageType.USER_INFO_TABLE,
				MessageType.USER_RULE_TABLE, MessageType.ORG_RULE_TABLE,
				MessageType.DATADICT_TABLE, MessageType.GOODS_TYPE_TABLE,
				MessageType.EFFECTIVE_TYPE_TABLE, MessageType.FREQUENCY_TABLE,
				MessageType.SCAN_RULE_TABLE, MessageType.SERVER_SMS_TYPE,
				MessageType.OFFLINE_LOGIN });

		context.startService(downIntent);
	}

	// 加数据头
	protected String build(String text) {
		if (text.length() > 6) {
			return text.substring(0, 6);
		} else {
			String s = "0";
			for (int i = 1; i < 6 - text.length(); i++) {
				s = s + "0";
			}
			return s + text;
		}
	}
}
